package com.example.demo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.PmAdjustManager;
import com.example.demo.entity.PmCompeteManager;
import com.example.demo.entity.PmEmployee;
import com.example.demo.entity.SysUser;
import com.example.demo.entity.excel.ExcelEntity;
import com.example.demo.mapper.PmAdjustManagerMapper;
import com.example.demo.mapper.PmCompeteManagerMapper;
import com.example.demo.mapper.PmEmployeeMapper;
import com.example.demo.service.impl.PmEmployeeServiceImpl;
import com.example.demo.utils.IDCardUtil;
import com.example.demo.utils.TokenUtils;
import com.sun.jmx.snmp.Timestamp;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/employee")
public class PmEmployeeController extends BaseController{

    @Resource
    PmEmployeeMapper pmEmployeeMapper;
    @Resource
    PmCompeteManagerMapper pmCompeteManagerMapper;
    @Resource
    PmAdjustManagerMapper pmAdjustManagerMapper;

    @Autowired
    PmEmployeeServiceImpl pmEmployeeService;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Timestamp d = new Timestamp(System.currentTimeMillis());
    Date date = new Date();
    String today = formatter.format(date);


    @PostMapping
    public synchronized Result<?> save(@RequestBody PmEmployee pmEmployee, HttpServletRequest request) {
        if (StrUtil.isBlank(pmEmployee.getProbationPeriod())){
            pmEmployee.setProbationPeriod("null,null");
            if (pmEmployee.getEmploymentType().contains("正式员工")){
                pmEmployee.setIsProbation("已转正");
                pmEmployee.setIsRegular(true);
            } else {
                pmEmployee.setIsProbation("特殊用工");
                pmEmployee.setIsRegular(false);
            }
        } else {
            String[] split = pmEmployee.getProbationPeriod().split(",");
            String endDate = split[1];
            if (today.compareTo(endDate) >= 0){
                pmEmployee.setIsProbation("已转正");
            }else {
                pmEmployee.setIsProbation("试用期");
            }
            pmEmployee.setIsRegular(true);
        }

        pmEmployee.setIsLeave(false);
        SysUser sysUser = TokenUtils.getUserInfo(request);
        if (sysUser == null)
            return Result.error("500", "未获取到user信息");
        pmEmployee.setAddUser(sysUser.getUsername());
        pmEmployee.setAddTime(formatter1.format(new Date()));
        pmEmployee.setIsDeleted(false);

        pmEmployeeMapper.insert(pmEmployee);
        return Result.success();
    }

    @PutMapping
    public synchronized Result<?> update(@RequestBody PmEmployee pmEmployee, HttpServletRequest request) {
        SysUser sysUser = TokenUtils.getUserInfo(request);
        if (sysUser == null)
            return Result.error("500", "未获取到user信息");

        if (!pmEmployee.getEmploymentType().contains("正式员工")){
            pmEmployee.setIsRegular(false);
            pmEmployee.setIsProbation("特殊用工");
        } else {
            pmEmployee.setIsRegular(true);
        }

        if (!pmEmployee.getIsLeave()){
            if (StrUtil.isNotBlank(pmEmployee.getProbationPeriod())) {
                String[] split = pmEmployee.getProbationPeriod().split(",");
                String endDate = split[1];
                if (endDate.equals("null")||today.compareTo(endDate) > 0){
                    pmEmployee.setIsProbation("已转正");
                }else {
                    pmEmployee.setIsProbation("试用期");
                }
            } else {
                pmEmployee.setIsProbation("已转正");
            }
        }else
            pmEmployee.setIsProbation("已离职");

        pmEmployee.setModifyUser(sysUser.getUsername());
        pmEmployee.setModifyTime(formatter1.format(new Date()));

        pmEmployeeMapper.updateById(pmEmployee);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public synchronized Result<?> delete(@PathVariable Long id, HttpServletRequest request) {
        SysUser sysUser = TokenUtils.getUserInfo(request);
        if (sysUser == null)
            return Result.error("500", "未获取到user信息");
        PmEmployee pmEmployee = pmEmployeeMapper.selectById(id);
//        pmEmployee.setIsDeleted(true);
        pmEmployee.setModifyTime(formatter1.format(date));
        pmEmployee.setModifyUser(sysUser.getUsername());
        pmEmployeeMapper.deleteById(id);
        return Result.success(pmEmployeeService.updateById(pmEmployee));
    }

    @GetMapping("/{id}")
    public synchronized Result<?> get(@PathVariable Long id) {
        return Result.success(pmEmployeeMapper.selectById(id));
    }

    @GetMapping("/list")
    public synchronized Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search,
                              @RequestParam(defaultValue = "") String phone,
                              @RequestParam(defaultValue = "") String company,
                              @RequestParam(defaultValue = "") String employmentType,
                              @RequestParam(defaultValue = "") String isLeave) {
        LambdaQueryWrapper<PmEmployee> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(PmEmployee::getName, search);
        }
        if (StrUtil.isNotBlank(company) && !StrUtil.equals(company,"会博集团及下属子公司")) {
            wrapper.eq(PmEmployee::getCompany, company);
        }
        if (StrUtil.isNotBlank(phone)) {
            wrapper.eq(PmEmployee::getPhone, phone);
        }
        if(StrUtil.isNotBlank(employmentType)){
            wrapper.like(PmEmployee::getEmploymentType, employmentType);
        }
        if(isLeave.equals("false")){
            wrapper.eq(PmEmployee::getIsLeave, true);
        }
        wrapper.eq(PmEmployee::getIsDeleted, false);
        Page<PmEmployee> pmEmployeePage = pmEmployeeMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(pmEmployeePage);
    }

    @ApiOperation(value = "导出excel表格", notes = "导出月度人员结构表")
    @GetMapping({"/export1/{startDate}/{endDate}/{company}"})
    public void exportInfo1(@PathVariable String startDate,
                            @PathVariable String endDate,
                            @PathVariable String company,
                            HttpServletResponse response) {
        Map<String, Object> excelMap;
        if (company.equals("会博集团及下属子公司")) company = "%";
        excelMap = pmEmployeeService.getMap1(startDate, endDate, company);
        if (company.equals("%")){
            excelMap.put("company", "会博集团及下属子公司");
        }else {
            excelMap.put("company", company);
        }
        Workbook workBook = null;
        try {
            TemplateExportParams params = new TemplateExportParams("static/pm/month_report.xlsx", true);
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("月度人员结构表.xlsx", "UTF-8"));
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        }finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出excel表格", notes = "导出月度人员流动统计表")
    @GetMapping("/export2/{startDate}/{endDate}/{name}/{company}")
    public void exportInfo2(@PathVariable String startDate,
                            @PathVariable String endDate,
                            @PathVariable String company,
                            @PathVariable String name,
                            HttpServletResponse response) {
        Map<String, Object> excelMap;
        if (company.equals("会博集团及下属子公司")) company = "%";
        excelMap = pmEmployeeService.getMap2(startDate, endDate, company);
        excelMap.put("name", name);
        if (company.equals("%")){
            excelMap.put("company", "会博集团及下属子公司");
        }else {
            excelMap.put("company", company);
        }
        TemplateExportParams params = new TemplateExportParams("static/pm/month_turnover.xlsx", true);
        Workbook workBook = null;
        try {
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
//            response.flushBuffer();
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("月度人员流动表.xlsx", "UTF-8"));
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        } finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出excel表格", notes = "导出新进员工清单表")
    @GetMapping("/export3/{startDate}/{endDate}/{company}")
    public void exportInfo3(@PathVariable String startDate,
                            @PathVariable String endDate,
                            @PathVariable String company,
                            HttpServletResponse response) {
        Map<String, Object> excelMap;
        if (company.equals("会博集团及下属子公司")) company = "%";
        excelMap = pmEmployeeService.getMap3(startDate, endDate, company);
        if (company.equals("%")){
            excelMap.put("company", "会博集团及下属子公司");
        }else {
            excelMap.put("company", company);
        }
        TemplateExportParams params = new TemplateExportParams("static/pm/new_employee.xlsx", true);
        Workbook workBook = null;
        try {
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
//            response.flushBuffer();
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("新进员工清单.xlsx", "UTF-8"));
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        } finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出excel表格", notes = "导出会博集团下属企业员工统计表")
    @GetMapping("/export4/{startDate}/{endDate}")
    public void exportInfo4(@PathVariable String startDate,
                            @PathVariable String endDate,
                            HttpServletResponse response) {
        Map<String, Object> excelMap = pmEmployeeService.getMap4(startDate, endDate);
        TemplateExportParams params = new TemplateExportParams("static/pm/group_statistics.xlsx", true);
        Workbook workBook = null;
        try {
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
//            response.flushBuffer();
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("会展集团人员信息统计表.xlsx", "UTF-8"));
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        } finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出excel表格", notes = "导出会博集团报送表")
    @GetMapping("/export5/{startDate}/{endDate}")
    public void exportInfo5(@PathVariable String startDate,
                            @PathVariable String endDate,
                            HttpServletResponse response) {
        Map<String, Object> excelMap = pmEmployeeService.getMap5(startDate, endDate);
        TemplateExportParams params = new TemplateExportParams("static/pm/submission_form.xlsx", true);
        Workbook workBook = null;
        try {
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
//            response.flushBuffer();
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("会展集团报送表.xlsx", "UTF-8"));
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        } finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "导出管理人员名单", notes = "导出管理人员名单")
    @GetMapping("/export6/{startDate}/{endDate}/{company}")
    public void exportInfo6(@PathVariable String startDate,
                            @PathVariable String endDate,
                            @PathVariable String company,
                            HttpServletResponse response) {
        if (company.equals("会博集团及下属子公司")) company = "%";
        Map<String, Object> excelMap = pmEmployeeService.getMap6(startDate, endDate, company);
        if (company.equals("%")){
            excelMap.put("company", "会博集团及下属子公司");
        }else {
            excelMap.put("company", company);
        }
        TemplateExportParams params = new TemplateExportParams("static/pm/manageTemplate.xlsx", true);
        Workbook workBook = null;
        try {
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("管理人员名单.xlsx", "UTF-8"));
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        } finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出管理人员名单", notes = "管理人员竞争上岗明细表")
    @GetMapping("/export7/{startDate}/{endDate}/{company}")
    public void exportInfo7(@PathVariable String startDate,
                            @PathVariable String endDate,
                            @PathVariable String company,
                            HttpServletResponse response) {
        if (company.equals("会博集团及下属子公司")) company = "%";
        Map<String, Object> excelMap = new HashMap<>();
        List<PmCompeteManager> list = pmCompeteManagerMapper.excel(startDate, endDate, company);
        List<PmCompeteManager> list1 = new ArrayList<>();
        int i = 1;
        for (PmCompeteManager item : list){
            long id = item.getEmployeeId();
            PmEmployee pmEmployee = pmEmployeeMapper.getById(id);
            if (!pmEmployee.getIsLeave() && !pmEmployee.getIsDeleted()) {
                item.setId(i);
                list1.add(item);
                i++;
            }
        }
        excelMap.put("start_date", startDate);
        excelMap.put("end_date", endDate);
        excelMap.put("list", list1);

        TemplateExportParams params = new TemplateExportParams("static/pm/compete_manager.xlsx", true);
        Workbook workBook = null;
        try {
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("管理人员竞争上岗明细表.xlsx", "UTF-8"));
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        } finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出管理人员名单", notes = "末等调整或不胜任退出清单明细表")
    @GetMapping({"/export8/{startDate}/{endDate}/{company}"})
    public void exportInfo8(@PathVariable String startDate,
                            @PathVariable String endDate,
                            @PathVariable String company,
                            HttpServletResponse response) {
        if (company.equals("会博集团及下属子公司")) company = "%";
        Map<String, Object> excelMap = new HashMap<>();
        List<PmAdjustManager> list = pmAdjustManagerMapper.excel(startDate, endDate, company);
        List<PmAdjustManager> list1 = new ArrayList<>();
        int i = 1;
        for (PmAdjustManager item : list){
            long id = item.getEmployeeId();
            PmEmployee pmEmployee = pmEmployeeMapper.getById(id);
            if (!pmEmployee.getIsDeleted()) {
                item.setId(i);
                list1.add(item);
                i++;
            }
        }
        excelMap.put("start_date", startDate);
        excelMap.put("end_date", endDate);
        excelMap.put("list", list1);

        TemplateExportParams params = new TemplateExportParams("static/pm/adjust_manager.xlsx", true);
        Workbook workBook = null;
        try {
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("末等调整或不胜任退出清单明细表.xlsx", "UTF-8"));
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        } finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导出花名册", notes = "导出员工花名册")
    @GetMapping({"/export9/{startDate}/{endDate}/{company}"})
    public void exportInfo9(@PathVariable String startDate,
                            @PathVariable String endDate,
                            @PathVariable String company,
                            HttpServletResponse response) {
        if (company.equals("会博集团及下属子公司")) company = "%";
        Map<String, Object> excelMap = pmEmployeeService.getMap7(startDate, endDate, company);
        if (company.equals("%")){
            excelMap.put("company", "会博集团及下属子公司");
        }else {
            excelMap.put("company", company);
        }
        TemplateExportParams params = new TemplateExportParams("static/pm/employee_info.xlsx", true);
        Workbook workBook = null;
        try {
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("员工花名册.xlsx", "UTF-8"));
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        } finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "下载人员导入模板", notes = "下载人员导入模板")
    @GetMapping("/download")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        ClassPathResource resource = new ClassPathResource("static/pm/employee_template.xlsx");
        InputStream in =resource.getInputStream();
        String fileName = "employee_template.xlsx";

        int len ;
        byte[] buffer = new byte[1024];
        response.setHeader("content-disposition", String.format("attachment; filename=%s", fileName));
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

        OutputStream out = response.getOutputStream();
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.flush();
        in.close();
    }


    @PostMapping("/import1")
    public Result<?> importExcel(MultipartFile file, HttpServletRequest request) throws Exception {
        SysUser sysUser = TokenUtils.getUserInfo(request);
        if (sysUser == null)
            return Result.error("500", "未获取到user信息");
        List<PmEmployee> pmEmployees = CollUtil.newArrayList();
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        InputStream inputStream = file.getInputStream();
        List<ExcelEntity> employees = ExcelImportUtil.importExcel(inputStream, ExcelEntity.class, params);
        int i = 1;
        try {
            for (ExcelEntity item : employees){
                if (item.getId() == null && item.getName() == null && item.getIdCard() == null && item.getPhone() == null && item.getDegree() == null)
                    continue;
                if (!item.getCompany().equals(sysUser.getCompany()))
                    return Result.error("401", "第" + i + "条公司名称有误，请核实信息！");
                if (item.getName() != null || item.getIdCard() != null){
                    PmEmployee pmEmployee = new PmEmployee();
                    LambdaQueryWrapper<PmEmployee> wrapper = Wrappers.lambdaQuery();
                    wrapper.eq(PmEmployee::getIdcardNumber, item.getIdCard())
                            .eq(PmEmployee::getIsDeleted, false)
                            .eq(PmEmployee::getCompany, sysUser.getCompany());
                    List<PmEmployee> list = pmEmployeeMapper.selectList(wrapper);
                    if (list.size() > 0) return Result.error("402", "该身份证号已有记录");

                    pmEmployee.setName(item.getName());
                    if (item.getIdCard().length() != 18) {
                        pmEmployee.setIdcardType("其他");
                        pmEmployee.setIdcardNumber(item.getIdCard());
                    } else if (StrUtil.isEmpty(item.getIdCard())){
                        return Result.error("401", "第" + i + "条证件信息没填有误！");
                    } else {
                        pmEmployee.setIdcardType("居民身份证");
                        pmEmployee.setIdcardNumber(item.getIdCard());
                        pmEmployee.setAge(IDCardUtil.getAge(pmEmployee.getIdcardNumber()));
                        pmEmployee.setSex(IDCardUtil.getSex(pmEmployee.getIdcardNumber()));
                        pmEmployee.setBirth(IDCardUtil.getBirthday(pmEmployee.getIdcardNumber()));
                    }

                    pmEmployee.setEthnic(item.getEthnic());
                    pmEmployee.setPhone(item.getPhone());
                    if (pmEmployee.getPhone().length() != 11) return Result.error("401", "第" + i + "条数据手机号码位数有误！");
                    pmEmployee.setDegree(item.getDegree());
                    pmEmployee.setGraduateSchool(item.getSchool());
                    pmEmployee.setMajor(item.getMajor());
                    pmEmployee.setDepartment(item.getDepartment());
                    pmEmployee.setPosition(item.getPosition());
                    pmEmployee.setProfessionalTitle(item.getTitle());
                    pmEmployee.setProfessionalCertificate(item.getCertificate());
                    pmEmployee.setEmploymentType(item.getMethod());
                    pmEmployee.setPositionStatus(item.getStatus());
//                    if (!pmEmployee.getEmploymentType().contains("正式员工") && !pmEmployee.getPositionStatus().equals("其他"))
//                        return Result.error("401", "第" + i + "条数据用工形式和岗序状况对应有误，实习生、劳务外包、退休返聘、兼职等人员岗序状态应设置为“其他”！");
//                    if (pmEmployee.getEmploymentType().contains("正式员工") && pmEmployee.getPositionStatus().equals("其他"))
//                        return Result.error("401", "第" + i + "条数据岗序状况有误，正式员工、正式员工-选聘高管不能设置为“其他”！");
                    pmEmployee.setWorkStartTime(item.getWorkTime());
                    pmEmployee.setHukouAddress(item.getHukou());
                    pmEmployee.setAncestralPlace(item.getNativePlace());
                    pmEmployee.setPoliticalStatus(item.getPolitical());
                    if (StrUtil.isEmpty(pmEmployee.getPositionStatus()))
                        pmEmployee.setPositionStatus("群众");
                    pmEmployee.setLeagueJoiningTime(item.getLeagueTime());
                    pmEmployee.setPartyJoiningTime(item.getPartyTime());
                    pmEmployee.setMaritalStatus(item.getMarriage());
                    pmEmployee.setAddress(item.getAddress());
                    pmEmployee.setOnboardingTime(item.getOnboardingTime());
                    pmEmployee.setRecruitmentSource(item.getOnboardingMethod());
                    pmEmployee.setStrongPoint(item.getStrong());
                    pmEmployee.setComment(item.getComment());
                    pmEmployee.setCompany(item.getCompany());

                    String start = item.getProbationStart();
                    String end = item.getProbationEnd();
                    String notice = item.getNoticeTime();
                    String publicTime = item.getPublicTime();
                    if (start != null){
                        if (end == null){
                            return Result.error("401", "请填写第" + i + "条记录的试用期结束时间");
                        } else {
                            if (start.compareTo(end) > 0)
                                return Result.error("401", "第" + i + "条数据试用期时间有误，试用结束时间早于开始时间！");
                            if (pmEmployee.getOnboardingTime().compareTo(start) > 0)
                                return Result.error("401", "第" + i + "条数据试用期时间有误，试用开始时间早于入职时间！");
                            if (pmEmployee.getEmploymentType().contains("正式员工")) {
                                if (today.compareTo(end) > 0){
                                    pmEmployee.setIsProbation("已转正");
                                    pmEmployee.setIsRegular(true);
                                } else {
                                    pmEmployee.setIsProbation("试用期");
                                    pmEmployee.setIsRegular(true);
                                }
                            } else {
                                pmEmployee.setIsProbation("特殊用工");
                                pmEmployee.setIsRegular(false);
                            }

                        }
                    }else {
                        if (pmEmployee.getEmploymentType().contains("正式员工")){
                            pmEmployee.setIsProbation("已转正");
                            pmEmployee.setIsRegular(true);
                        } else {
                            pmEmployee.setIsProbation("特殊用工");
                            pmEmployee.setIsRegular(false);
                        }
                    }
                    pmEmployee.setProbationPeriod(start + "," + end);

                    if (pmEmployee.getEmploymentType().contains("正式员工")) {
                        if (StrUtil.isEmpty(pmEmployee.getRecruitmentSource())) {
                            return Result.error("401", "第" + i + "条数据是正式员工，但没有填写入职方式");
                        }
                    }

                    if (notice != null){
                        if (publicTime != null && notice.compareTo(publicTime) > 0)
                            return Result.error("401", "第" + i + "条数据招聘公告时间和录用公示时间有误，公示时间早于公告时间！");
                        if (publicTime != null && publicTime.compareTo(pmEmployee.getOnboardingTime()) > 0)
                            return Result.error("401", "第" + i + "条数据录用公示时间和入职时间有误，入职时间早于公示时间！");
                        if (notice.compareTo(pmEmployee.getOnboardingTime()) > 0)
                            return Result.error("401", "第" + i + "条数据招聘公告和入职时间有误，入职时间早于公告时间！");
                    }
                    pmEmployee.setAnnouncementTime(notice);
                    pmEmployee.setPublicityTime(publicTime);
                    pmEmployee.setAddUser(sysUser.getUsername());
                    pmEmployee.setAddTime(formatter1.format(new Date()));
                    pmEmployee.setIsLeave(false);

                    pmEmployees.add(pmEmployee);
                }else {
                    return Result.error("401", "第" + i + "条数据姓名/身份证号信息缺失！");
                }
                i++;
            }
        }catch (Exception e){
            return Result.error("401", "请使用模板文件。");
        }
        if(pmEmployeeService.saveOrUpdateBatch(pmEmployees)){
            return Result.success();
        }else{
            return Result.error("5001","导入失败");
        }
    }
}

